package com.example.ndktest;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;

public class AudioPlayer implements Runnable, Consumer{

	private boolean isRunning;
	private Object mutexDataAvailable = new Object();
	private LinkedList<short[]> list;
	private AudioTrack m_out_trk ;
	private int        m_out_buf_size ;
	private NetReceiver netReceiver;
	private static final int frequency = Configuration.FREQUENCY;
	private static final int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;
	
	public AudioPlayer()
	{
		super();
		list = new LinkedList<short[]>();
		
		m_out_buf_size = android.media.AudioTrack.getMinBufferSize(frequency,
                AudioFormat.CHANNEL_CONFIGURATION_MONO,
                audioEncoding);
		
		m_out_trk = new AudioTrack(AudioManager.STREAM_VOICE_CALL, frequency,
                AudioFormat.CHANNEL_CONFIGURATION_MONO,
                audioEncoding, 
                m_out_buf_size,
                AudioTrack.MODE_STREAM);
		
		isRunning = true;
		
	}
	
	private void startNetReceiver()
	{
		netReceiver = new NetReceiver(this, 4562);
		Thread thread = new Thread(netReceiver);
		thread.start();
	}
	
	@Override
	public void putData(long ts, byte[] buf, int size) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void putDecodedData(long tx, short[] buf, int size) {
		// TODO Auto-generated method stub
		short temp[] = new short[size];
		System.arraycopy(buf, 0, temp, 0, size);
		list.add(temp);
	}

	@Override
	public void setRecording(boolean isRecording) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean isRecording() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		
		startNetReceiver();
		m_out_trk.play();
		
		while(isRunning)
		{
			try
			{
				if(list.size() > 0)
				{
					short[] decodedBuf = list.removeFirst();
					m_out_trk.write(decodedBuf, 0, decodedBuf.length);
				}
				else
				{
					Thread.sleep(20);
				}
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
		}
	}

	public void stop()
	{
		isRunning = false;
	}
	
	public void dataAvailable()
	{
		try{
			mutexDataAvailable.notify();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
